package superpay

import (
	//"encoding/json"
	"errors"
	"strings"
	"thirdpaysdk/utils/mapstruct"
	//"thirdpaysdk/wxpay"
	"thirdpaysdk/utils/signature"
	"github.com/astaxie/beego"
)

/*
gmt_create=20181026174439&gmt_payment=20181026174438&notify_time=20181026180906&outer_trade_no=275705784002678784&_input_charset=UTF-8&sign=2D9AA8CFD86F177EE967553D728230DD&version=1.0&notify_id=ac73495fb5d14051a2194c454365e3d9&notify_type=trade_status_sync&trade_amount=0.02+AUD&inner_trade_no=101154053627146341580&trade_status=TRADE_FINISHED&sign_type=MD5
*/

type SuperPayMsg struct {
	NotifyId     string  `form:"notify_id"`             // 通知的唯一标识
	NotifyType   string  `form:"notify_type"`           // 通知类型
	NotifyTime   string  `form:"notify_time"`           // 通知时间
	InputCharset string  `form:"_input_charset"`        // 参数字符集编码
	Sign         string  `form:"sign"`                  // 签名
	SignType     string  `form:"sign_type"`             // 签名方式
	Version      string  `form:"version"`               // 版本号
	OuterTradeNo string  `form:"outer_trade_no"`        // 商户网站唯一订单号/商户网站退款唯一订单号(退款通知)
	InnerTradeNo string  `form:"inner_trade_no"`        // 钱包交易号/钱包退款交易号(退款通知)
	TradeStatus  string  `form:"trade_status"`          // 交易状态
	TradeAmount  string  `form:"trade_amount"`          // 交易金额
	TradeInfo    string  `form:"trade_info,omitempty"`  // 交易详情
	GmtCreate    string  `form:"gmt_create"`            // 交易创建时间
	GmtPayment   string  `form:"gmt_payment,omitempty"` // 交易支付时间
	GmtClose     string  `form:"gmt_close,omitempty"`   // 交易关闭时间
	//以下为退款通知独有参数
	OrigOuterTradeN string  `form:"orig_outer_trade_n,omitempty"` // 原交易商户网站唯一订单号
	RefundAmount    string  `form:"refund_amount,omitempty"`      // 退款金额
	RefundStatus    string  `form:"refund_status,omitempty"`      // 退款状态
	GmtRefund       string  `form:"gmt_refund,omitempty"`         // 交易退款时间
}

func SuperpayNotify(msg *SuperPayMsg, mchId, appKey string) (map[string]interface{}, error){
	rspMap :=  mapstruct.Struct2Map(msg, "form")
	appSecret := appKey
	sign := signature.SuperPayMakeSign(rspMap, appSecret)
	result := strings.EqualFold(msg.Sign, sign)
	if !result {
		beego.Debug("msg.Sign:",msg.Sign,"sign:",sign)
		returnMsg := "sign is invalid"
		return map[string]interface{}{}, errors.New(returnMsg)
	}
	return rspMap, nil
}
